/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2024-03-21 15:58:22
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-22 19:04:29
 * @FilePath: /yt-devops/lib/pages/mine/system_set/security/change_password/change_password_controller.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sprintf/sprintf.dart';
import 'package:yt_devops/components/string_extension.dart';
import 'package:yt_devops/components/yt_input.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/auth/auth_services.dart';
import 'package:yt_devops/user_entity_manager.dart';

class ChangePasswordController extends GetxController {
  AuthServices authServices = AuthServices();

  TextEditingController oldPasswordController = TextEditingController();

  TextEditingController newPasswordController = TextEditingController();

  TextEditingController confirmPasswordController = TextEditingController();



  String oldHintText = ResKey.plsEnterOldPwd.tr;

  String newHintText = ResKey.plsEnterNewPwd.tr;

  String confirmHintText = ResKey.plsConfirmNewPwd.tr;



  String title = ResKey.changePassword.tr;

  bool buttonEnable = false;

  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  textOnChange() {
    buttonEnable = oldPasswordController.text.isNotEmpty &&
        newPasswordController.text.isNotEmpty &&
        confirmPasswordController.text.isNotEmpty;
    update();
  }

  YtInputValidateResult validatePassword(String str) {
    if (str.tyIsPassword) {
      return YtInputValidateResult(succes: true, errorMessqge: '');
    } else {
      return YtInputValidateResult(
          succes: false, errorMessqge:ResKey.pwdFormatError.tr);
    }
  }

  YtInputValidateResult validateSamePassword(String str) {
    if (newPasswordController.text == confirmPasswordController.text) {
      return YtInputValidateResult(succes: true, errorMessqge: '');
    } else {
      return YtInputValidateResult(succes: false, errorMessqge: ResKey.pwdIsDifferent.tr);
    }
  }

  save() => Configs.httpClient.requestWithLoading(() async {
        if (formKey.currentState?.validate() == true) {
          await authServices.updatePwd({
            'oldPassword': oldPasswordController.text,
            'newPassword': newPasswordController.text,
          });
          await UserEntityManager().cleanAuth();
          Get.offAllNamed(RouterPath.login);
        }
      });
}
